import fs from 'fs';
import path from 'path';

interface UploadRecord {
    filename: string;
    path: string;
    uploadTime: string;
}

interface Database {
    uploads: UploadRecord[];
}

export class FileDB {
    private dbFile: string;
    private data: Database;

    constructor() {
        this.dbFile = path.join(__dirname, 'uploads.json');
        this.data = this.initializeDB();
    }

    private initializeDB(): Database {
        if (!fs.existsSync(this.dbFile)) {
            const initialData = { uploads: [] };
            fs.writeFileSync(this.dbFile, JSON.stringify(initialData, null, 2));
            return initialData;
        }
        const data = fs.readFileSync(this.dbFile, 'utf-8');
        return JSON.parse(data);
    }

    private saveDB(): void {
        fs.writeFileSync(this.dbFile, JSON.stringify(this.data, null, 2));
    }

    // 添加新的上传记录
    addUpload(filename: string, filePath: string): UploadRecord {
        const record: UploadRecord = {
            filename,
            path: filePath,
            uploadTime: new Date().toISOString()
        };
        this.data.uploads.push(record);
        this.saveDB();
        return record;
    }

    // 获取所有上传记录
    getAllUploads(): UploadRecord[] {
        return this.data.uploads;
    }

    // 根据文件名查找记录
    findByFilename(filename: string): UploadRecord | undefined {
        return this.data.uploads.find(record => record.filename === filename);
    }

    // 获取最新的上传记录
    getLatestUpload(): UploadRecord | undefined {
        return this.data.uploads[this.data.uploads.length - 1];
    }
    // 获取最新的excel记录
    getLatestExcelUpload(): UploadRecord | undefined {
        return this.data.uploads.find(record => record.filename.endsWith('.xlsx'));
    }
    
}

// 导出单例实例
export const fileDB = new FileDB(); 